package br.com.hsp.system.beans;

import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import br.com.hsp.system.repository.AtendenteInstituicaoRepository; 
import br.com.hsp.users.AtendenteInstituicao ;


@ManagedBean
public class AtendenteInsBean {

	private AtendenteInstituicao atendenteI = new AtendenteInstituicao();
	
	private List<AtendenteInstituicao> atendenteIs; 

	public void add() {
		EntityManager manager = this.getManager();
		AtendenteInstituicaoRepository atendenteIRepository = new AtendenteInstituicaoRepository(manager);

		if (this.atendenteI.getId() == null) {
			atendenteIRepository.add(this.atendenteI);
		} else {
			atendenteIRepository.atualiza(this.atendenteI);
		}
		this.atendenteI = new AtendenteInstituicao ();
	}

	public void preparaAlteracao() {
		Map<String, String> params = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		AtendenteInstituicaoRepository repository = new AtendenteInstituicaoRepository(manager);
		this.atendenteI = repository.procura(id);

	}
	

	public void remove() {
		Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		AtendenteInstituicaoRepository repository = new AtendenteInstituicaoRepository(manager);
		repository.remove(id);
		this.atendenteI = null;
		this.atendenteIs = null;
	}
	

	private EntityManager getManager() {
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ec.getRequest();
		return (EntityManager) request.getAttribute("EntityManager");

	}

	public List<AtendenteInstituicao > getAtendenteIs() {
		if (this.atendenteIs == null) {
			EntityManager manager = this.getManager();
			AtendenteInstituicaoRepository repository = new AtendenteInstituicaoRepository(manager);
			this.atendenteIs = repository.getLista();
		}
		return this.atendenteIs;
	}

	public AtendenteInstituicao  getAtendenteI() {
		return atendenteI;
	}

	public void setAtendenteI(AtendenteInstituicao  atendenteI) {
		this.atendenteI = atendenteI;
	}

}
